package tako.wisers.com.android.apis.location;

import java.util.List;

import tako.wisers.com.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.view.View;
import android.view.View.OnClickListener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class OverlayControl {
	private MapView mMapView;

	private Drawable mMarker;

	private int mMarkerXOffset;

	private int mMarkerYOffset;

	private List<Overlay> overlays;

	public OverlayControl(MapView mapView) {
		mMapView = mapView;
		overlays = mMapView.getOverlays();
	}

	public void build(Activity activity) {
		// Make sure to give mMarker bounds so it will draw in the overlay
		mMarker = activity.getResources().getDrawable(R.drawable.map_pin);
		final int intrinsicWidth = mMarker.getIntrinsicWidth();
		final int intrinsicHeight = mMarker.getIntrinsicHeight();
		mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight);

		mMarkerXOffset = -(intrinsicWidth / 2);
		mMarkerYOffset = -intrinsicHeight;
	}

	public void setOverlay(Location location) {
		overlays.add(new PanoramioOverlay(location));
	}

	public void setOverlay(GeoPoint point) {
		overlays.add(new PanoramioOverlay(point));
	}

	public void setMyLocationOverlay(Context context) {
		MyLocationOverlay mMyLocationOverlay = new MyLocationOverlay(context,
				mMapView);
		overlays.add(mMyLocationOverlay);
	}

	public void Invalidate() {
		mMapView.invalidate();
	}
	
	public void setZoom(int zoom){
		mMapView.getController().setZoom(zoom);
	}

	class PanoramioOverlay extends Overlay {
		private GeoPoint mPoint;

		public PanoramioOverlay(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lon = (int) (location.getLongitude() * 1E6);
			mPoint = new GeoPoint(lat, lon);
		}

		public PanoramioOverlay(GeoPoint point) {
			mPoint = point;
		}

		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection p = mapView.getProjection();
			p.toPixels(mPoint, point);
			super.draw(canvas, mapView, shadow);
			drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y
					+ mMarkerYOffset, shadow);
		}
	}

	public void clearOverlay() {
		overlays.clear();
	}

}
